package IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import data.Episode;
import data.Show;
import Error.Error;

public class Read 
{
	public static Vector<Show> showsXML = null;
	 
	public static boolean isShowListNull()
	{
		return (showsXML == null);
	}
	public static void closeShowList()
	{
		showsXML = null;
	}
	//Need a better way of reading this to remove the warning!
	public static Vector<Show> readShows()
	{
		return Read.readXMLShows("showsXML");
	}
	public static Vector<Show> readShows(String file)
	{
		Vector<Show> returnShowVector = Read.showsXML;
		if(returnShowVector == null)
		{
			return Read.readXMLShows(file);
		}
		return returnShowVector;
	}
	
	public static Vector<Show> readXMLShows(String fileName)
	{
		Vector<Show> showList = new Vector<Show>();
		String showsFile = SystemInfo.getApplicationDirectory() + fileName +".xml";		
		
		 try {
			  File file = new File(showsFile);
			  if(!file.exists())
			  {
				  Error.report(12);
				  return null;
			  }
			  InputStream inputStream= new FileInputStream(file);
			  Reader reader = new InputStreamReader(inputStream,"UTF-8");
			  InputSource is = new InputSource(reader);
			  is.setEncoding("UTF-8");
			  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			  DocumentBuilder db = dbf.newDocumentBuilder();
			  Document doc = db.parse(is);
			  doc.getDocumentElement().normalize();
			  NodeList showNodeList = doc.getElementsByTagName("show");
			  for (int k = 0; k < showNodeList.getLength(); k++) 
			  {
				  Node showNode = (Element)showNodeList.item(k);
				  String showName;
				  Show s = null;
				  int selectedSeason = 0;
				  if(showNode.getNodeType() == Element.ELEMENT_NODE)
				  {
					  Element showNodeElement = (Element)showNode;
					  showName = getElementValue(showNodeElement, "showName");
					  String selectedSeasonString = getElementValue(showNodeElement, "selectedSeason");
					  if(selectedSeasonString != null)
					  {
						  selectedSeason = Integer.parseInt(selectedSeasonString);  
					  }
					  NodeList seasonNodeList = showNodeElement.getElementsByTagName("season");
					  s = new Show(showName);
					  for(int i=0; i < seasonNodeList.getLength(); i++)
					  {
						  Node seasonNode = (Element)seasonNodeList.item(i);
						  int seasonNumber;
						  int selectedEpisode = 0;
						  if(seasonNode.getNodeType() == Element.ELEMENT_NODE)
						  {
							  Element seasonNodeElement = (Element)seasonNode;
							  seasonNumber = Integer.parseInt(getElementValue(seasonNodeElement, "seasonNumber"));
							  String selectedEpisodeString = getElementValue(seasonNodeElement, "selectedEpisode");
							  if(selectedEpisodeString != "")
							  {
								  selectedEpisode = Integer.parseInt(selectedEpisodeString);
							  }
							  NodeList epNodeList = seasonNodeElement.getElementsByTagName("episode");
							  for(int j=0; j < epNodeList.getLength(); j++)
							  {
								  Element epNode = (Element)epNodeList.item(j);
								  int epNum;
								  String epTitle;
								  String torrentURL;
								  String description;
								  Date airdate;
								  epNum = Integer.parseInt(getElementValue(epNode, "episodeNumber"));
								  epTitle = getElementValue(epNode, "title");
								  torrentURL = getElementValue(epNode, "url");
								  description = getElementValue(epNode, "description");
								  String hasDownloaded = getElementValue(epNode, "hasDownloaded");
								  SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd kk:mm:ss Z yyyy");
								  String airDateString = getElementValue(epNode, "airdate");
								  airdate = dateFormat.parse(airDateString);
								  epTitle.toString();
								  Episode e = new Episode(epNum, epTitle, torrentURL, description, airdate);
								  e.setDownloaded(hasDownloaded.equals("true"));
								  s.addEpisode(e, seasonNumber);
							  }  
							  if(selectedEpisode != 0 && selectedSeason != 0)
							  {
								  s.setSelectedEpisode(selectedSeason, selectedEpisode);
							  }
							  else
							  {
								  s.setPreferedSelectedEpisode(true, false);
							  }
						  }
					  }
				  }
				  showList.add(s);
			  }
		 }
		 catch(Exception e)
		 {
			 e.printStackTrace();
		 }
		 return showList;
	}

	public static String getElementValue(Element parent,String label) 
	{
		return getCharacterDataFromElement((Element)parent.getElementsByTagName(label).item(0));
	}
	public static String getCharacterDataFromElement(Element e) 
	{
		try 
		{
			Node child = e.getFirstChild();
			if(child instanceof CharacterData) 
			{
				CharacterData cd = (CharacterData) child;
				return cd.getData();
			}
		}
		catch(Exception ex) 
		{}
		return "";
	}
}
